package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import gripper.ftp.FtpSession;

public class STATHandle implements Handle {
	FtpSession ftpSession;
	static SimpleDateFormat sdf = new SimpleDateFormat("MMM dd HH:mm", Locale.ENGLISH);

	public STATHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String[] splited = line.split(" ");
		if (splited == null || splited.length < 2) {
			os.write("450 path do not exist.\r\n".getBytes());
			os.flush();
			return;
		}
		String fileName = splited[1].trim();
		fileName = ftpSession.currentDir + "/" + fileName;
		File file = new File(fileName);
		if (!file.exists()) {
			os.write("450 path do not exist.\r\n".getBytes());
			os.flush();
			return;
		}
		if (file.isDirectory()) {
			os.write("213 File status okay; about to open data connection.\r\n".getBytes());
			File[] files = file.listFiles();
			for (File f : files) {
				String template = "#{dir}rwxr--r--   1 user     group        #{size} #{date} #{fileName}\r\n";
				long time = f.lastModified();
				Date date = new Date(time);
				template = template.replace("#{date}", sdf.format(date));
				template = template.replace("#{fileName}", f.getName());
				if (f.isDirectory()) {
					template = template.replace("#{dir}", "d");
					template = template.replace("#{size}", "1024");
				} else {
					template = template.replace("#{dir}", "-");
					template = template.replace("#{size}", Long.toString(f.length()));
				}
				os.write(template.getBytes());
			}
			os.write("213 End of Status\r\n".getBytes());
			os.flush();
			return;
		} else {
			os.write("450 path do not exist.\r\n".getBytes());
			os.flush();
			return;
		}
	}

}